package com.glory.brepda.activity.mfg;

import android.content.DialogInterface;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.BinInfoListAdapter;
import com.glory.brepda.adapter.LastBatchAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.BinInfoEntity;
import com.glory.brepda.entity.EdcEntity;
import com.glory.brepda.entity.EdcSetBinEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author lenovo
 */
public class FTDataSortActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWork)
    EditText etEqpWork;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvGetData)
    TextView tvGetData;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvBINInfoList)
    RecyclerView rvBINInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private ArrayList<EdcEntity.EdcSet> edcList = new ArrayList<>();
    private BinInfoListAdapter mBinInfoListAdapter;
    private LotInfoEntity mLoInfoEntity;
    private EdcEntity body;
    private String totalqty;
    private List<EdcSetBinEntity> edcsetbinlinelist;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ftdata_sort;
    }

    @Override
    protected void initView() {
        listTv1.setText("BIN名称");
        listTv2.setText("BIN描述");
        listTv3.setText("数量");
        listTv4.setText("占比良率");
        initRecyclerView(rvBINInfoList,this);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);
        mBinInfoListAdapter = new BinInfoListAdapter(null,true);
        mBinInfoListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mBinInfoListAdapter.isFirstOnly(true);
        rvBINInfoList.setAdapter(mBinInfoListAdapter);

        initEdit(etLot, s -> LotUtils.searchLotInfo(FTDataSortActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                tvNum.setText(response.getLOT().getMAINQTY());
                mBinInfoListAdapter.setMainQTY(Integer.parseInt(response.getLOT().getMAINQTY()));
                mLoInfoEntity = response;

                requestEdcData();
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"LOTQUERY");
            }
        }));
    }

    private void requestEdcData() {
//        String ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"LOTID\":\"20G2589-1-012\",\"PARTNAME\":\"FN62301\",\"STEPNAME\":\"T1110\",\"EDCSETLIST\":[{\"EDCSETNAME\":\"836_BIN1-8\",\"EDCSETDESCRIPTION\":\"836_BIN1-8\",\"EDCTYPE\":\"BIN\",\"EDCSETBINLINELIST\":[{\"NAME\":\"BIN1\",\"DESCRIPTION\":\"良品\",\"SPECTYPE\":\"PERCENT\",\"LSL\":\"98.00\",\"BINTYPE\":\"P\",\"ACTIONPARAM1\":\"A\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN2\",\"DESCRIPTION\":\"OS不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN3\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.40\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN4\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"1.50\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN5\",\"DESCRIPTION\":\"FT不良品\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.30\",\"BINTYPE\":\"F\",\"BINGROUP\":\"BIN3_4_5\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN6\",\"DESCRIPTION\":\"QA不良品\",\"USL\":\"0.00\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN7\",\"DESCRIPTION\":\"印字不良\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN8\",\"DESCRIPTION\":\"引脚不良\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN9\",\"DESCRIPTION\":\"少数（虚拟BIN）\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN10\",\"DESCRIPTION\":\"报废（虚拟BIN）\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN11\",\"DESCRIPTION\":\"样品\",\"BINTYPE\":\"P\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN12\",\"DESCRIPTION\":\"未测BIN\",\"BINTYPE\":\"P\",\"BINACTION\":\"Split\"},{\"NAME\":\"BIN3_4_5\",\"DESCRIPTION\":\"FT不良BIN组\",\"SPECTYPE\":\"PERCENT\",\"USL\":\"2.0\",\"BINTYPE\":\"G\",\"BINACTION\":\"None\"},{\"NAME\":\"BIN13\",\"DESCRIPTION\":\"掉料(虚拟BIN)\",\"USL\":\"0.50\",\"BINTYPE\":\"F\",\"BINACTION\":\"Scrap\"},{\"NAME\":\"BIN99\",\"SPECTYPE\":\"PERCENT\",\"BINTYPE\":\"O\",\"BINACTION\":\"None\"}]}]}}}";
//        BaseResponseBean<EdcEntity> dd = (new Gson()).fromJson(ss, new TypeToken<BaseResponseBean<EdcEntity>>() {
//        }.getType());
//        if (dd.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//            body = dd.getResponse().getBody();
//            if (body.getEDCSETLIST().get(0).getEDCTYPE().equals("BIN")){
//                edcSetBinAdapter.setNewData(body.getEDCSETLIST().get(0).getEDCSETITEMLINELIST());
//            }else {
//                showConfirmDialog(FTOffLineDataSortActivity.this,"只支持BIN数据类型采集");
//            }
//        }
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    body = response.body().getResponse().getBody();
                    edcList.addAll(body.getEDCSETLIST());
                    totalqty = String.valueOf(body.getTOTALQTY());
                    getData();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"CPCGETEDCCURRENT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOTID",getText(etLot));
        NetUtils.requestPostNet("IF.EDCCURRENT","Common",FTDataSortActivity.this,map,callBack);
    }

    private void getData() {
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    if (response.body().getResponse().getBody().getEDCSETLIST().size() <= 0){
                        showConfirmDialog("暂无数据");
                        return;
                    }
                    edcsetbinlinelist = response.body().getResponse().getBody().getEDCSETLIST().get(0).getEDCSETBINLINELIST();
                    ArrayList<BinInfoEntity.BinInfo> binInfos = new ArrayList<>();
                    for (EdcSetBinEntity s:response.body().getResponse().getBody().getEDCSETLIST().get(0).getEDCSETBINLINELIST()) {
                        binInfos.add(new BinInfoEntity.BinInfo(s.getNAME(),s.getDESCRIPTION(),s.getVALUE()));
                    }
                    mBinInfoListAdapter.setNewData(binInfos);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "RTM.BINRESULTREQUEST");
            }
        };

        JsonObject map = new JsonObject();
//                map.addProperty("EQUIPMENTID",getText(etEqpWork));
        map.addProperty("LOTID",getText(etLot));
        map.add("EDCSETLIST", new JsonParser().parse(new Gson().toJson(edcList)).getAsJsonArray());
        NetUtils.requestPostNet("RTM.BINRESULTREQUEST","BINRESULTREQUEST",FTDataSortActivity.this,map,callBack);

    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.tvBaseSubmit, R.id.tvGetData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit26"))return;

                if (getText(etLot).equals("")) {
                    showToast("请先扫描批次ID", false);
                    return;
                }

                if (mLoInfoEntity == null) {
                    showToast("未获取到批次信息，请重新扫描批次号",false);
                    return;
                }

                if (mBinInfoListAdapter.getData().size() <= 0){
                    showToast("请先获取数据",false);
                    return;
                }

                double sum = 0;
                for (BinInfoEntity.BinInfo entity:mBinInfoListAdapter.getData()){
                    if (entity.getBINNO().equals("BIN99")){
                        continue;
                    }
                    sum += entity.getBINQTY();
                }

                int lotNum = Integer.parseInt(tvNum.getText().toString());

                if (sum != lotNum){
                    showConfirmDialog("Total不等于BIN的总数！差值：" + String.valueOf(lotNum - sum));
                    return;
                }

                showSubmitDialog(() -> submit(getText(etLot), getText(etEqpWork), mLoInfoEntity, mBinInfoListAdapter.getData()));

                break;
            case R.id.tvGetData:
                if (getText(etLot).equals("")){
                    showToast("批次ID不能为空",false);
                    return;
                }

                FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                        (new TypeToken<BaseResponseBean<EdcEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            if (response.body().getResponse().getBody().getEDCSETLIST().size() <= 0){
                                showConfirmDialog("暂无数据");
                                return;
                            }
                            edcsetbinlinelist = response.body().getResponse().getBody().getEDCSETLIST().get(0).getEDCSETBINLINELIST();
                            ArrayList<BinInfoEntity.BinInfo> binInfos = new ArrayList<>();
                            for (EdcSetBinEntity s:response.body().getResponse().getBody().getEDCSETLIST().get(0).getEDCSETBINLINELIST()) {
                                binInfos.add(new BinInfoEntity.BinInfo(s.getNAME(),s.getDESCRIPTION(),s.getVALUE()));
                            }
                            mBinInfoListAdapter.setNewData(binInfos);
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "RTM.BINRESULTREQUEST");
                    }
                };

                JsonObject map = new JsonObject();
//                map.addProperty("EQUIPMENTID",getText(etEqpWork));
                map.addProperty("LOTID",getText(etLot));
                map.add("EDCSETLIST", new JsonParser().parse(new Gson().toJson(edcList)).getAsJsonArray());
                NetUtils.requestPostNet("RTM.BINRESULTREQUEST","BINRESULTREQUEST",FTDataSortActivity.this,map,callBack);
                break;
//            case R.id.tvSynchronous:
//                for (BinInfoEntity.BinInfo entity : mBinInfoListAdapter.getData()){
//                    if (entity.getBINNO().equals("BIN99")){
//                        synchronous(mBinInfoListAdapter.getData().indexOf(entity));
//                        return;
//                    }
//                }
//                showToast("未找到BIN99，无法同步",false);
//                break;
        }
    }

    private void synchronous(int position) {
        List<BinInfoEntity.BinInfo> data = mBinInfoListAdapter.getData();
        //修改BIN2得数量
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getBINNO().equals("BIN2")){
                BinInfoEntity.BinInfo entity = data.get(i);
                entity.setBINQTY(entity.getBINQTY() - body.getDAWBQTY());
                mBinInfoListAdapter.notifyItemChanged(i);
                break;
            }
        }
        //修改BIN99得数量
        mBinInfoListAdapter.getData().get(position).setBINQTY(body.getDAWBQTY());
        mBinInfoListAdapter.notifyItemChanged(position);
        showToast("同步成功",true);
        tvGetData.setVisibility(View.GONE);
    }

    private void submit(String lotID, String eqpID,LotInfoEntity lotInfoEntity,List<BinInfoEntity.BinInfo> binList) {
        FreeUI_EntityCallBack<BaseResponseBean<EdcEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EdcEntity>>
                (new TypeToken<BaseResponseBean<EdcEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EdcEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    String ruleMsg = "";
                    if (response.body().getResponse().getBody()!= null && response.body().getResponse().getBody().getRuleMsg().equals("低良进待决")){
                        ruleMsg = ",低良进待决";
                    }
                    FreeApi_ToastUtils.showFreeToast("提交成功"+ruleMsg,FTDataSortActivity.this,true,0);
                    FTDataSortActivity.this.finish();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EdcEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"INTEGRATIONSUBMIT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("LOTID",getText(etLot));
        map.addProperty("ISTEMP",false);
        map.addProperty("ISRMS",false);
        map.addProperty("TOTALQTY",totalqty);
        List<EdcEntity.EdcSet> edcsetlist = body.getEDCSETLIST();
        for (int i = 0; i < mBinInfoListAdapter.getData().size() - 1; i++) {
            edcsetbinlinelist.get(i).setVALUE(mBinInfoListAdapter.getData().get(i).getBINQTY());
        }
        edcsetlist.get(0).setEDCSETBINLINELIST(edcsetbinlinelist);
        map.add("EDCSETLIST",new JsonParser().parse(new Gson().toJson(binList)).getAsJsonArray());
        NetUtils.requestPostNet("IF.SAVEEDCDATA","DataIntegrationFt",FTDataSortActivity.this,map,callBack);

    }
}
